#ifndef _PTR_HELP_H_
#define _PTR_HELP_H_

template <typename T>
class CPtr
{
protected:
    struct CData
    {
        CData(T* p):pT(p),lRef(1){}
        ~CData(){ delete pT; }
        T* pT;
        LONG lRef;
    };
public:
    CPtr()
    {
        m_pData = NULL;
    }
    CPtr(T* pT)
    {
        m_pData = new CData(pT);
    }
    CPtr(const CPtr& cT)
    {
        if (NULL != cT.m_pData &&
            InterlockedIncrement(&cT.m_pData->lRef) > 0)
        {
            m_pData = cT.m_pData;
        }
        else
        {
            m_pData = NULL;
        }
    }
    ~CPtr()
    {
        if (NULL != m_pData &&
            InterlockedDecrement(&m_pData->lRef) <= 0)
        {
            delete m_pData;
        }
    }
    CPtr& operator=(const CPtr cT)
    {
        if (NULL != m_pData &&
            InterlockedDecrement(&m_pData->lRef) <= 0)
        {
            delete m_pData;
        }
        if (NULL != cT.m_pData &&
            InterlockedIncrement(&cT.m_pData->lRef) > 0)
        {
            m_pData = cT.m_pData;
        }
        else
        {
            m_pData = NULL;
        }
        return *this;
    }
    operator T*()
    {
        if (NULL != m_pData) return m_pData->pT;
        else return NULL;
    }
    T* operator ->()
    {
        if (NULL != m_pData) return m_pData->pT;
        else return NULL;
    }
private:
    CData* m_pData;
};

#endif // _PTR_HELP_H_